package com.cty.queue;
/*
*用数组模拟环形队列解决数组复用问题
* */

public class CircleArrayQueue {
    private int maxSize;
    private int front;//队列头指向队列的头元素，默认是0可以不写
    private int rear;//队列尾指向队列尾元素的后一个位置，默认是0可以不写
    private int [] arr;
    //初始化环形队列
    public CircleArrayQueue(int maxSize){
        this.maxSize=maxSize;
        arr=new int[maxSize];//初始化数组
    }
    //判满方法
    public boolean isFull(){
        return (rear+1)%maxSize==front;
    }
    //判空方法
    public boolean isEmpty(){
        return front==rear;
    }
    //存入数据
    public void addQueue(int num){
        if(isFull()){
            System.out.println("队列已满~~~~");
            return;
        }
        arr[rear]=num;
        //解决环形队列的数组索引越界的问题
        rear=(rear+1)%maxSize;
    }
    //取数据
    public int getQueue(){
        if(isEmpty()) {
           throw new RuntimeException("队列为空");
        }
        //先将队列中原值储存之后在指针后移
        int value=arr[front];
        //解决环形队列的数组索引越界的问题
        front=(front+1)%maxSize;
        return value;
    }
    //遍历环形队列
    public void ListQueue(){
        if (isEmpty()) {
            throw new RuntimeException("队列为空~~");
        }
        //解决环形队列数组索引越界的问题
        for (int i = front; i < front+size(); i++) {
            System.out.printf("arr[%d]=%d\n",i,arr[i]);
        }
    }
    //返回环形队列中有效值的个数
    public int size(){
        return (rear+maxSize-front)%maxSize;
    }
    //查看队列的头数据(注意不是获取)
    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("队列为空~~~");
        }
        return arr[front];
    }


}
